import { expect, getFileContent, rspackTest, test } from '@e2e/helper';

rspackTest('should apply defer by default', async ({ build }) => {
  const rsbuild = await build();
  const files = rsbuild.getDistFiles();
  const html = getFileContent(files, 'index.html');

  expect(html).toContain('<script defer src="');
});

test('should remove defer when scriptLoading is "blocking"', async ({
  build,
}) => {
  const rsbuild = await build({
    config: {
      html: {
        scriptLoading: 'blocking',
      },
    },
  });
  const files = rsbuild.getDistFiles();
  const html = getFileContent(files, 'index.html');

  expect(html).toContain('<script src="');
});

test('should allow to set scriptLoading to "module"', async ({ build }) => {
  const rsbuild = await build({
    config: {
      html: {
        scriptLoading: 'module',
      },
    },
  });
  const files = rsbuild.getDistFiles();
  const html = getFileContent(files, 'index.html');

  expect(html).toContain('<script type="module" src="');
});

test('should not affect existing script tags in HTML template', async ({
  build,
}) => {
  const rsbuild = await build({
    config: {
      output: {
        filenameHash: false,
      },
      html: {
        template: './src/index.html',
        scriptLoading: 'module',
      },
    },
  });
  const files = rsbuild.getDistFiles();
  const html = getFileContent(files, 'index.html');
  expect(html).toContain(
    '<script async src="https://example.com/foo.js"></script>',
  );
  expect(html).toContain(
    '<script type="module" src="/static/js/index.js"></script>',
  );
});

test('should not affect tags generated by `html.tags`', async ({ build }) => {
  const rsbuild = await build({
    config: {
      output: {
        filenameHash: false,
      },
      html: {
        scriptLoading: 'module',
        tags: [
          {
            tag: 'script',
            attrs: {
              src: 'https://example.com/foo.js',
              async: true,
            },
          },
        ],
      },
    },
  });

  const files = rsbuild.getDistFiles();
  const html = getFileContent(files, 'index.html');
  expect(html).toContain(
    '<script src="https://example.com/foo.js" async></script>',
  );
  expect(html).toContain(
    '<script type="module" src="/static/js/index.js"></script>',
  );
});
